<template>
  <div>
    <keep-alive>
    <router-view v-if="$route.meta.keepAlive" />
  </keep-alive>
  <router-view v-if="!$route.meta.keepAlive"/>
  </div>
 
</template>

<script>
import { initDynamicRoutes } from "@/router/index";
import {  userLogout,logUpdate } from "@/api/api.js";

import qs from "qs";
import axios from 'axios';
import router from "./router/index"


export default {
  name: "App",
  data(){
    return{
      _beforeUnload_time:0,
      _gap_time:0,
      closeT:false
    }
  },
  mounted(){
    this.newValue=sessionStorage.getItem('username')
    if(this.newValue!=null){
      this.closeT=false
      console.log("执行loginUpDate")
      this.loginUpDate()
      
    }
    window.addEventListener('setItem',(e)=>{
      console.log('storage变化',e)
      this.newValue=sessionStorage.getItem('username')
      if(this.newValue!=''){
        this.closeT=false
        this.loginUpDate()
        
      }
    })
    window.addEventListener('clear',(e)=>{
      console.log('storage清空',e)
      clearInterval(this.cancelTimes)
    })
    //this.loginUpDate()
   
  },
  watch:{
    closeT(newValue){
      if(newValue==true){
        clearInterval(this.cancelTimes)
      }
    }
  },
  created() {
    // console.log('创建App.vue')
    // 在页面加载时读取sessionStorage里的状态信息
    if (sessionStorage.getItem("store")) {
      this.$store.replaceState(
        Object.assign(
          {},
          this.$store.state,
          JSON.parse(sessionStorage.getItem("store"))
        )
      );
    }

    // 在页面刷新时将vuex里的信息保存到sessionStorage里
    // beforeunload事件在页面刷新时先触发
    
    window.addEventListener("beforeunload", (e) => {
      sessionStorage.setItem("store", JSON.stringify(this.$store.state));
      this.beforeunloadHandler(e)
    });
    
    window.addEventListener('unload',   (e) =>  this.unloadHandler(e))
    // 在vue组件创建时调用添加动态路由的方法
    // initDynamicRoutes();
  },
  destroyed(){
          
    window.removeEventListener("beforeunload", (e) => {
      this.beforeunloadHandler(e);
    });
    
    window.removeEventListener('unload',   (e) =>  this.unloadHandler(e))
  },
  methods:{
    
    beforeunloadHandler(e) {
      const storage=window.localStorage
      storage.clear()
      this._beforeUnload_time=new Date().getTime();
     
          
      
    },
    loginUpDate(){
      
      return this.cancelTimes= setInterval(()=>{
        var date=new Date()
        var h=date.getHours()
        var m=date.getMinutes()
        var s=date.getSeconds()
        console.log('更新',h+':'+m+":"+s)

        var userId=''
          if(sessionStorage.getItem('selectRole')){
          userId=sessionStorage.getItem('selectRole')
          }
          else{
            userId=this.$store.state.username
          }

          logUpdate({id:userId}).then(res=>{
                        console.log("结果",res);
                        const { code, result } = res.data
                        if (code === '0000') {
                            
                        }
                        else{
                            this.closeT=true
                            this.$store.commit("resetState");
                            // 清理sessionStorage
                            sessionStorage.clear();
                            this.$resetSetItem('clear','22222')
                            localStorage.clear()
                            this.$alert(res.data.errmessage, "提示", {
                              confirmButtonText: "确认",
                              callback: (action) => {
                                router.push("/");
                              },
                            });
                            
                          }
                        
                })
      },60000)
      
    },
     unloadHandler(e){
      
        this._gap_time=new Date().getTime()-this._beforeUnload_time;
        console.log('关闭')
        
        debugger
        //判断是窗口关闭还是刷新
        if(this._gap_time<=5){
          

          //如果是登录状态，关闭窗口前，移除用户
          var id_t=''
          clearInterval(this.loginUpDate)
          if(sessionStorage.getItem('selectRole')){
            id_t=sessionStorage.getItem('selectRole')
          }
          else{
            id_t=this.$store.state.username
          }
          var params={id:id_t}
          var req=qs.stringify(params)
          
          fetch('http://8.142.80.180:8081/user/logout?'+req, {
            method: 'get',
            
            headers: {'Content-Type': 'application/json'},
            keepalive: true
        });
        
        //navigator.sendBeacon('http://8.142.80.180:8081/user/logout?'+req)
        
       /* $.ajax({
          url:'/user/logout?'+req,
          type:'get',
          
          async:false
        })*/
       /*var xhttp=new XMLHttpRequest()
       xhttp.onreadystatechange=function(){
        if (xhttp.readyState == 4 && xhttp.status == 200) {
          console.log(xhttp.responseText)
        }
       }
       xhttp.open('GET','http://8.142.80.180:8081/user/logout?'+req,false)
        xhttp.send(null)*/
        
      
        /*await new Promise((resolve,reject)=>{
              userLogout({id:id_t}).then((res) => {
                  resolve(res.data)
                  const { code, result } = res.data;
                  if (code === "0000") {
                    console.log("退出!",result);
                    
                    this.$store.commit("resetState");

                    // 清理sessionStorage
                    sessionStorage.clear();
                    this.$resetSetItem('clear','22222')
                    this.$router.go(0)
                  }
                })
         })*/
          
         
          console.log('debugger')
          
          
        } 
      },

  }
};
</script>

<style>
html,
body {
  margin: 0px;
  padding: 0px;
  height: 100%;
}


#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 0px;
}
</style>
